<template>
  <div class="block-image" :class="{'uploading': status != 'upload-success'}">
    <image v-if="isShowPreview" :src="block.path" mode="widthFix"></image>
    <div v-if="isShowProgressBar" class="block-progress">
      图片上传中...{{percentTip}}%
    </div>
    <file-upload v-if="block.status == 'temp'" :path="block.path"
      :size="block.size"
      dir="materials/pics"
      content-type="image/*"
      type="image"
      @progress="onProgress"
      @start="status = 'uploading'"
      @success="onUploadSuccess"
    ></file-upload>
  </div>
</template>

<script>
import FileUpload from './file-upload'

export default {
  props: {
    block: {
      type: Object,
      default () {
        return {
          path: '',
          size: 0,
          status: '',
          type: 'pic',
        }
      }
    }
  },
  components: {
    FileUpload
  },
  data () {
    return {
      percent: 0,
    }
  },
  computed: {
    status () {
      if (this.block.status === 'enable') {
        return 'upload-success'
      }
      return 'temp'
    },
    isShowProgressBar () {
      if (this.block.status === 'temp') return true
      if (this.status === 'uploading') return true
      if (this.block.status === 'animation') return false
      return false
    },
    isShowPreview () {
      if ((this.status === 'upload-success' || this.block.status === 'animation') && this.block.path) return true
      return false
    },
    percentTip () {
      return parseInt(this.percent * 100)
    }
  },
  watch: {
    percent (nv) {
      if (nv === 1) {
        this.status = 'upload-success'
      }
    }
  },
  methods: {
    onProgress (info) {
      this.percent = info.percent
    },
    onUploadSuccess (material) {
      this.$emit('upload-success', material)
    }
  }
}
</script>

<style scoped lang="less">
@import '../assets/less/var.less';
.block-image {
  position: relative;
  .mask {
    position: absolute;
    z-index: 10;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255,255,255, .9);
    z-index: 10;
  }
}
.progress {
  position: absolute;
  padding: 12px;
  background-color: rgba(0,0,0,.5);
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  progress {
    position: relative;
    top: 48%;
  }
}
</style>
